os = require 'os'
fs = require 'fs-extra'
fsp = require '../libs/fs-promises'
path = require 'path'
lessc = require './lessc'
pr = path.resolve
Handlebars = require 'handlebars'
_ = require 'underscore'
Q = require 'q'
express = require 'express'

# 获取命令行参数
program = require 'commander'
program
  .version('0.0.1')
  .option('-c, --context <context>', 'web app context')
  .option('-p, --project <path>', 'Path for project development.')
  .option('-k, --appkey <key>', 'App Key')
  .option('-o, --override <override>', 'allow project resource override server resource')
  .parse(process.argv)

module.exports = (app, prefix, workdir) ->
  app.use path.join(prefix, 'vendor'), express.static path.resolve(workdir, 'static', 'vendor')
  app.get prefix, (req, res) ->
    # list the components directory and send them to the template
    root = path.join(pr(workdir), 'static/runtime/js/components')
    root2 = path.join(pr(workdir), 'js/components')
    stylesDir = path.join(pr(workdir), 'configure/styles')
    components = []
    styles = []
    Q.all [
      fsp.traverse_safe root, relative: true
      .then (all) ->
        all.sort().forEach (each) ->
          components.push(each.replace('.js', ''));

      fsp.traverse_safe root2, relative: true
      .then (all) ->
        all.sort().forEach (each) ->
          components.push(each.replace('.js', ''));

      fsp.traverse_safe stylesDir, relative: true
      .then (all) ->
        all.forEach (each) ->
          styles.push(each) if each.endsWith '.css';
    ]
    .then ->
      res.render 'inspectors', {
        'components': components,
        'styles': styles
      }
    .catch (err) ->
      console.trace err
      callback(err)

# 画布：供iframe中使用
  app.get path.join(prefix, '/canvas.html'), (req, res) ->

    fsp.readdir_safe path.resolve(program.project, "less")
    .then (styles) ->
      # styles是less目录下的文件名列表
      # 先过滤出less文件
      # 再将后缀转为css，让其匹配后台less即时编译路由
      styles = _.chain(styles).filter (file)->
        !file.startsWith('_') and file.endsWith('.less') # _开头的不加载
      .map (style) ->
        style.replace('.less', '.css')
      .value()
      res.render 'runtime/runtime-canvas', {
        prefix: '../runtime',
        styles: styles
      }
  # 支持及时编译less接口，浏览器依旧请求css，接口负责即时编译
  app.get path.join(prefix, 'css/:name.css'), (req, res, next) ->
    # less编译
    less_file = path.resolve(program.project, "less", "#{req.params.name}.less")
    fsp.stat less_file
    .then ->
      # 编译less
      console.log "lessc: #{less_file}"
      lessc.render less_file
      .then (output) -> res.set('Content-Type', 'text/css').send(output.css)
      .catch (err) ->
        next(err)
    .catch (err) ->
      # less文件不存在，跳过
      console.log "less file: #{req.params.name} not found, pass"
      next()

# produce a fake app.js, TODO generate more useful app.js response
  app.get path.join(prefix, 'app.js'), (req, res, next) ->
    appjs = "window.app = {}"
    res.set('Content-Type', 'application/javascript').send(appjs)
